import com.fasterxml.jackson.databind.ObjectMapper;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

class User{
     public  String username;
     public    String password;
     public   String nickname;
     public   String operation;
 }
class QueryResult{
    public  String username;
    public    String password;
    public   String nickname;
    public   String operation;
}

  @WebServlet("/hello")
public class ServletPost extends HttpServlet {
        //通过 ObjectMapper 解析 和 构造 JSON 对象
     private ObjectMapper ObjectMapper = new ObjectMapper();
   // private List<User> users = new ArrayList<>();

      // 如果有查询函数的调用 把 queryResult 置为 true
      boolean queryResult = false;
      // 保存查询的数据
      List<QueryResult> queryResults = null;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //从请求流中读到数据内容，并把数据转换成 User 类
        User user = ObjectMapper.readValue(req.getInputStream(),User.class);
        System.out.println(user.username);
        System.out.println(user.operation);

        //通过 ContentType 告知页面，返回的数据是 JSON 格式
        resp.setContentType("application/json;charset=utf8");
        if("添加".equals(user.operation)){
            save(user);
        }else if("删除".equals(user.operation)){
            delete(user.username);
        }else if("修改".equals(user.operation)){
            System.out.println("-----------");
            System.out.println(user.username);
            System.out.println(user.password);
            System.out.println(user.operation);
            System.out.println("-----------");

            update(user);
        }else if("查询".equals(user.operation)){
             queryResults=query(user.username);
            queryResult = true;
        }


        resp.getWriter().write("{\"ok\":true}");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       List<User> users = load();
       String jsonString = ObjectMapper.writeValueAsString(users);

       String queryJsonString = ObjectMapper.writeValueAsString(queryResults);

        resp.setContentType("application/json;charset=utf8");
        if(queryResult){
            resp.getWriter().write(queryJsonString);
            System.out.println("queryJsonString"+"："+queryJsonString);
            System.out.println(queryResult);
            queryResult=false;
            System.out.println(queryResult);

        }else{
            System.out.println("hellojsonString");
            System.out.println(jsonString);
            resp.getWriter().write(jsonString);
        }


    }

      //把一条数据添加进数据库
      private void save(User user)  {
          Connection connection = null;
          PreparedStatement statement = null;
          try {
              //和数据库建立连接
              connection = DBUtil.getConnection();
              //构造语句
              String sql = "insert into admin values(?,?,?)";
              statement = connection.prepareStatement(sql);
              statement.setString(1,user.username);
              statement.setString(2,user.password);
              statement.setString(3,user.nickname);
              //执行 SQL 语句
              statement.executeUpdate();
          } catch (SQLException e){
              e.printStackTrace();
          }finally {
              DBUtil.close(connection,statement,null);
          }
      }


      public boolean delete(String  username) {
          Connection connection = null;
          PreparedStatement statement = null;

          try {
              //和数据库建立连接
              connection = DBUtil.getConnection();
              //构造语句
              String sql=" delete from admin where username=?";
              statement = connection.prepareStatement(sql);
              statement.setString(1,username);
              //执行 SQL 语句
              statement.executeUpdate();
          } catch (SQLException throwables) {
              throwables.printStackTrace();
          }finally {
              DBUtil.close(connection,statement,null);
          }
          return false;
      }

      public boolean update(User user) {

          Connection connection = null;
          PreparedStatement statement = null;

          try {
              //和数据库建立连接
              connection = DBUtil.getConnection() ;
              //构造语句
              String sql="update admin set nickname = ?,password = ? where username = ?";
              statement = connection.prepareStatement(sql);
              statement.setString(1,user.nickname);
              statement.setString(2,user.password);
              statement.setString(3,user.username);
              //执行 SQL 语句
              statement.executeUpdate();
          } catch (SQLException e) {
              e.printStackTrace();
          }finally {
              DBUtil.close(connection,statement,null);
          }

          return false;
      }
      // 查询
      public List<QueryResult> query(String username) {
          List<QueryResult> queryResults = new ArrayList<>();

          Connection connection=null;
          PreparedStatement statement=null;
          ResultSet resultSet = null;
          try {
              //和数据库建立连接
              connection= DBUtil.getConnection();
              //构造语句
              String sql=" select * from admin where username=?";
              statement = connection.prepareStatement(sql);
              statement.setString(1,username);
              //执行 SQL 语句
              resultSet = statement.executeQuery();
              while (resultSet.next()){
                  QueryResult queryResult = new QueryResult();
                  queryResult.username = resultSet.getString("username");
                  queryResult.password = resultSet.getString("password");
                  queryResult.nickname = resultSet.getString("nickname");
                  queryResults.add(queryResult);
              }



          } catch (SQLException throwables) {
              throwables.printStackTrace();
          }finally {
             // queryResult = true;

              DBUtil.close(connection,statement,null);
          }
          return queryResults;
      }

//      //把数据库中的数据全部加载出来
      private List<User> load(){
          List<User> users = new ArrayList<>();
          Connection connection = null;
          PreparedStatement statement = null;
          ResultSet resultSet = null;
          try {
              //和数据库建立连接
              connection = DBUtil.getConnection();
              //构造语句
              String sql = "select * from admin";
              statement = connection.prepareStatement(sql);
              //执行 SQL 语句
              resultSet = statement.executeQuery();
              while (resultSet.next()){
                  User user = new User();
                  user.username = resultSet.getString("username");
                  user.password = resultSet.getString("password");
                  user.nickname = resultSet.getString("nickname");
                  users.add(user);
              }
          } catch (SQLException e){
              e.printStackTrace();
          }finally {
              DBUtil.close(connection,statement,null);
          }
          return users;
      }

}
